package com.TLLT.QADMobileItemEnquiry;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.text.method.KeyListener;
import android.text.method.NumberKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class LoginFragment extends Fragment {
	
	public static EditText textHost;
	private DataDataSource datasource;
	public static EditText LoginTxt;
	public static EditText PassTxt;
	public static CheckBox remember;
	static KeyListener kl;
	public static Button btLogin;
	Table values;
	Context ctx;
	static RelativeLayout progressLayout;
	static LoginWSTask lgt;
	static Intent intent ;
	AlertDialog dialog ;
	
	public static LoginFragment newInstance(int index) {
		LoginFragment f = new LoginFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }
    

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }
        ctx=getActivity().getBaseContext();
        
        RelativeLayout relative = new RelativeLayout(getActivity().getApplicationContext());
          
        View loginLayout = inflater.inflate(R.layout.login_tab, null);
        relative.addView(loginLayout);
        getLoginView(loginLayout);
        
        View progressLayout = inflater.inflate(R.layout.progressbar, null);
        relative.addView(progressLayout);
        getProgressView(progressLayout);
        
        return relative;
    }
    
    public void getProgressView(View v){
    	progressLayout = (RelativeLayout) v.findViewById(R.id.progressLayout);
    }
    
    public void getLoginView(View v) {
		LoginTxt = (EditText) v.findViewById(R.id.editTextLogin);
		PassTxt = (EditText) v.findViewById(R.id.editTextPassword);
		remember = (CheckBox) v.findViewById(R.id.checkBoxRemember);
		textHost = (EditText) v.findViewById(R.id.editTextHost);

		datasource = new DataDataSource(ctx);
		datasource.open();

		try {
			values = datasource.getTable("4");
			if (!values.getData().equals("0")
					&& values.getData().equals("true")) {
				remember.setChecked(true);
			} else {
				remember.setChecked(false);
			}
		} catch (Exception ex) {
			remember.setChecked(false);
		}

		if (remember.isChecked()) {
			try {
				values = datasource.getTable("2");
				LoginTxt.setText(values.getData(), TextView.BufferType.EDITABLE);
				values = datasource.getTable("3");
				PassTxt.setText(values.getData(), TextView.BufferType.EDITABLE);
			} catch (Exception ex) {
			}
		}

		try {
			values = datasource.getTable("1");
			
			if (!values.getData().equals("0")) {
				textHost.setText(values.getData(), TextView.BufferType.EDITABLE);
			} else {
				textHost.setText(getResources().getString(R.string.editViewWSHost),
						TextView.BufferType.EDITABLE);
			}
		} catch (Exception ex) {
			textHost.setText(getResources().getString(R.string.editViewWSHost), TextView.BufferType.EDITABLE);
		}

	    btLogin = (Button) v.findViewById(R.id.buttonLogin);
		btLogin.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				DataExchangeControler.initURL(textHost.getText().toString());
				datasource.updateTable("1",
						String.valueOf(textHost.getText().toString()));
				
				lgt=new LoginWSTask();
			     lgt.execute(LoginTxt.getText().toString(),PassTxt.getText().toString());
				
				
			}
		});
	}
	
	void lounchScaning(){
		intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.putExtra("SCAN_FORMATS","EAN_8,UPC_A,UPC_E,EAN_13,CODE_39,CODE_93,CODE_128,DATA_MATRIX,ITF,CODABAR");
		getActivity().startActivityForResult(intent, 0);
	}
	
	public static void editableLoginForm(Boolean editable){
		NumberKeyListener nkl=new NumberKeyListener() {
		    public int getInputType() {
		        return InputType.TYPE_NULL;
		    }

		    protected char[] getAcceptedChars() {
		        return new char[] {};
		    }
		};
		if (editable==false){
		kl=PassTxt.getKeyListener();
		textHost.setKeyListener(nkl);
		LoginTxt.setKeyListener(nkl);
		PassTxt.setKeyListener(nkl);
		}else{
			textHost.setKeyListener(kl);
			LoginTxt.setKeyListener(kl);	
			PassTxt.setKeyListener(kl);	
		}
		remember.setClickable(editable);
		btLogin.setClickable(editable);
		if (editable)
		{ progressLayout.setVisibility(View.INVISIBLE); }
		else {
			progressLayout.setVisibility(View.VISIBLE);
		}
	}
	
		

	class LoginWSTask extends AsyncTask<String, String, String> {
		
		@Override
		protected void onPreExecute(){
			editableLoginForm(false);
		}
		
		@Override
		protected void onPostExecute(String result)
	    {
			super.onPreExecute();
			if (LoginControler.logedin) {
				
				  Context context = ctx; CharSequence text ="You loged in successfully!"; 
				  int duration = Toast.LENGTH_SHORT; 
				  Toast toast = Toast.makeText(context,text, duration); 
				  toast.show();
				 
				datasource.updateTable("4",String.valueOf(remember.isChecked()));
				if (remember.isChecked()) {
					datasource.updateTable("2",
							String.valueOf(LoginTxt.getText().toString()));
					datasource.updateTable("3",
							String.valueOf(PassTxt.getText().toString()));
					Main.logedIn=true;
					lounchScaning();
					
				} else {

					datasource.updateTable("2", String.valueOf(""));
					datasource.updateTable("3", String.valueOf(""));
					Main.logedIn=true;
					lounchScaning();
				}


			} else { 
				
				  if (LoginControler.message.contains("timed")){((Main)getActivity()).showAlert(R.string.connection_timeout_message);}
				  else{
					  ((Main)getActivity()).showAlert(R.string.incorrect_login_message);
				  }
				  Main.logedIn=false;
				 } 
			editableLoginForm(true);
	    }
		
		@Override
		protected String doInBackground(String... params) {
			String usr=(String)params[0];
			String psw=(String)params[1];
			String msg = LoginControler.login(usr,psw );

			
			return "success";
		}
		}
}
